package com.project.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.biz.CmsOrderBiz;
import com.project.biz.CmsRecoveryMemberRechargeBiz;
import com.project.util.AesUtil;
import com.project.util.wx.WxPaySignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Description:
 * @Author: zhuchi
 * @CreateDate: 2020/12/3 15:27
 * @Version: 1.0
 */
@ApiIgnore
@RestController
@Slf4j
public class WxPayController {

    /**
     * 商品订单业务层接口类
     */
    @Autowired
    private CmsOrderBiz orderBiz;

    /**
     * 回收员充值业务层接口类
     */
    @Autowired
    private CmsRecoveryMemberRechargeBiz recoveryMemberRechargeBiz;

    /**
     * 微信支付成功通知
     * @param notifyData
     * @return
     */
    @PostMapping(value = "/wx/payNotify")
    public JSONObject wxPayNotify(@RequestBody JSONObject notifyData){
        log.info("微信支付成功通知,接收到参数:{}", notifyData);
        JSONObject returnData = new JSONObject();

        String apiV3Key = WxPaySignUtil.API_V3_KEY;

        try {
            byte[] apiV3KeyByte = apiV3Key.getBytes("utf-8");
            AesUtil aesUtil = new AesUtil(apiV3KeyByte);

            JSONObject resource = notifyData.getJSONObject("resource");
            //附加数据
            String associated_data = resource.getString("associated_data");

            //随机串
            String nonce = resource.getString("nonce");

            //数据密文
            String ciphertext = resource.getString("ciphertext");

            //密文解密
            String decryptCiphertext = aesUtil.decryptToString(associated_data.getBytes(), nonce.getBytes(), ciphertext);
            log.info("微信支付成功通知中密文解密后内容:{}", decryptCiphertext);
            JSONObject decryptCiphertextJson = JSONObject.parseObject(decryptCiphertext);

            //交易状态（SUCCESS：成功,REFUND:转入退款,NOTPAY:未支付,CLOSED:已关闭,REVOKED:已撤销（付款码支付）,USERPAYING:用户支付中（付款码支付）,PAYERROR:支付失败(其他原因，如银行返回失败)）
            String trade_state = decryptCiphertextJson.getString("trade_state");
            if ("SUCCESS".equals(trade_state)){
                //0:失败,1:成功,2:已处理过,3:订单不存在
                int result = this.orderBiz.updateOrderH5PayNotify(decryptCiphertextJson);
                if (result == 1 || result == 2){
                    returnData.put("code", "SUCCESS");
                    returnData.put("message", "成功");
                }else {
                    returnData.put("code", "ERROR");
                    returnData.put("message", "失败");
                }
            }else {
                returnData.put("code", "ERROR");
                returnData.put("message", "失败");
            }
        }catch (Exception e){
            log.info("微信支付成功通知,对密文数据解密时发生错误:{}", e.getMessage());
            returnData.put("code", "ERROR");
            returnData.put("message", "失败");
        }

        return returnData;
    }

    /**
     * 回收员充值支付成功异步通知
     * @param notifyData
     * @return
     */
    @PostMapping(value = "/wx/recoveryPayNotify")
    public JSONObject recoveryPayNotify(@RequestBody JSONObject notifyData){
        log.info("回收员充值支付成功异步通知,接收到参数:{}", notifyData);
        JSONObject returnData = new JSONObject();

        String apiV3Key = WxPaySignUtil.API_V3_KEY;

        try {
            byte[] apiV3KeyByte = apiV3Key.getBytes("utf-8");
            AesUtil aesUtil = new AesUtil(apiV3KeyByte);

            JSONObject resource = notifyData.getJSONObject("resource");
            //附加数据
            String associated_data = resource.getString("associated_data");

            //随机串
            String nonce = resource.getString("nonce");

            //数据密文
            String ciphertext = resource.getString("ciphertext");

            //密文解密
            String decryptCiphertext = aesUtil.decryptToString(associated_data.getBytes(), nonce.getBytes(), ciphertext);
            log.info("回收员充值支付成功异步通知中密文解密后内容:{}", decryptCiphertext);
            JSONObject decryptCiphertextJson = JSONObject.parseObject(decryptCiphertext);

            //交易状态（SUCCESS：成功,REFUND:转入退款,NOTPAY:未支付,CLOSED:已关闭,REVOKED:已撤销（付款码支付）,USERPAYING:用户支付中（付款码支付）,PAYERROR:支付失败(其他原因，如银行返回失败)）
            String trade_state = decryptCiphertextJson.getString("trade_state");
            if ("SUCCESS".equals(trade_state)){
                //0:失败,1:成功,2:已处理过,3:订单不存在
                int result = this.recoveryMemberRechargeBiz.updateRecoveryMemberRechargeNotify(decryptCiphertextJson);
                if (result == 1 || result == 2){
                    returnData.put("code", "SUCCESS");
                    returnData.put("message", "成功");
                }else {
                    returnData.put("message", "失败");
                    returnData.put("code", "ERROR");
                }
            }else {
                returnData.put("code", "ERROR");
                returnData.put("message", "失败");
            }
        }catch (Exception e){
            log.info("回收员充值支付成功异步通知,对密文数据解密时发生错误:{}", e.getMessage());
            returnData.put("code", "ERROR");
            returnData.put("message", "失败");
        }

        return returnData;
    }
}
